package com.card.hwatt.dao.impt;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.card.hwatt.dao.*;
import com.card.hwatt.dto.PageResult;
import com.card.hwatt.entity.*;

@Repository("leaveDao")
public class LeaveDaoImpt extends BaseDaoImpt<Leave> implements LeaveDao {

	@Override
	public PageResult<Object[]> loadAllGroup(int departmentId, String name,
			String startDate, String endDate, int page, int rows) {
		PageResult<Object[]> result = new PageResult<Object[]>();

		StringBuilder hql = new StringBuilder(
				" from Leave a join a.employee b ");

		hql.append(" where (a.employee.department.path like :path ) ");
		if (StringUtils.isNotEmpty(name)) {
			hql.append(" and (a.employee.name like :name or a.employee.employeeCode like :code ) ");
		}
		if (StringUtils.isNotEmpty(startDate)
				&& StringUtils.isNotEmpty(endDate)) {
			hql.append(" and ( date >= :start and date < :end ) ");
		}
		hql.append(" group by a.employee , a.value , a.date ");

		Session session = getCurrentSession();

		Query totalQuery = session.createQuery("select a.value "
				+ hql.toString());

		setGroupParameter(hql, departmentId, totalQuery, name, startDate,
				endDate);

		@SuppressWarnings("rawtypes")
		List total = totalQuery.list();
		result.total = total.size();

		hql.append(" order by a.date desc ");

		Query query = session
				.createQuery(" select max(b) , a.value , a.date , max(a.key) , min(a.name) , max(a.name) , count(*),  max(a.reason) "
						+ hql.toString());
		query = query.setFirstResult(rows * (page - 1)).setMaxResults(rows);
		setGroupParameter(hql, departmentId, query, name, startDate, endDate);

		@SuppressWarnings("unchecked")
		List<Object[]> list = query.list();

		result.rows = list;
		return result;
	}

	private void setGroupParameter(StringBuilder hql, int departmentId,
			Query query, String name, String startDate, String endDate) {

		query.setParameter("path", "%@" + departmentId + "@%");

		if (hql.indexOf(":name") >= 0) {
			query.setParameter("name", "%" + name + "%");
		}
		if (hql.indexOf(":code") >= 0) {
			query.setParameter("code", "%" + name + "%");
		}

		String[] parsePatterns = { "yyyy-MM-dd", "yyyy-M-dd", "yyyy-M-d" };
		if (hql.indexOf(":start") >= 0) {
			try {
				Date start = DateUtils.parseDate(startDate, parsePatterns);
				query.setParameter("start", new java.sql.Date(start.getTime()));
			} catch (Exception e) {
			}

		}
		if (hql.indexOf(":end") >= 0) {
			try {
				Date end = DateUtils.parseDate(endDate, parsePatterns);
				query.setParameter("end", new java.sql.Date(end.getTime()));
			} catch (Exception e) {
			}

		}
	}
}
